package com.whately.core.redis.utils;

import com.whately.core.base.model.RedisKeyBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created by craig.qin on 2018/9/20.
 */
@Component
public class RedisTemplateUtils {
    private final Logger logger = LoggerFactory.getLogger(RedisTemplateUtils.class);

    @Autowired
    private StringRedisTemplate redisTemplate;

    public StringRedisTemplate getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**************************************************************************
     *     hash
     *************************************************************************/


    /**************************************************************************
     *     list
     *************************************************************************/

    /**************************************************************************
     *     set
     *************************************************************************/



    /**************************************************************************
     *     通用
     *************************************************************************/


    /**
     * 实现命令：TTL key，以秒为单位，返回给定 key的剩余生存时间(TTL, time to live)。
     * @param cacheKey
     * @return
     */
    public long ttl(RedisKeyBuilder cacheKey) {
        return redisTemplate.getExpire(cacheKey.getKey());
    }

    /**
     * 实现命令：expire 设置过期时间，单位秒
     *
     * @param cacheKey
     * @return
     */
    public void expire(RedisKeyBuilder cacheKey, long timeout) {
        redisTemplate.expire(cacheKey.getKey(), timeout, TimeUnit.SECONDS);
    }


    /**
     * 实现命令：expire 设置过期时间
     *
     * @param cacheKey
     * @return
     */
    public void expire(RedisKeyBuilder cacheKey, long timeout, TimeUnit timeUnit) {
        redisTemplate.expire(cacheKey.getKey(), timeout, timeUnit);
    }

    /**
     * 实现命令：DEL key，删除一个key
     *
     * @param cacheKey
     */
    public void delete(RedisKeyBuilder cacheKey) {
        redisTemplate.delete(cacheKey.getKey());
    }

    public boolean hasKey(RedisKeyBuilder cacheKey){
        return redisTemplate.hasKey(cacheKey.getKey());
    }


}
